import React from 'react';
import { inject, observer } from 'mobx-react';
import * as mobx from 'mobx';
import './index.less';
import { getAntd, getEcCom, getComsMobx, getLabel } from '../../../util/convert';
import { Radio } from 'antd';
const RadioGroup = Radio.Group;
import NodeInfo from './NodeInfoDialog';
import * as type from '../../../constants/type';

@inject('globalStore', 'selectNextFlowStore')
@observer
export default class Main extends React.Component {
    constructor() {
        super();
        this.state = {
            isSubmit: false,
            radiovalue:''
        };
    }

    componentDidMount() {
        const { selectNextFlowStore } = this.props;
        selectNextFlowStore.doInit();
    }
    render() {
        const { Button, message } = getAntd();
        const { WeaDialogFooter, WeaRightMenu, WeaSearchGroup, WeaFormItem, BaseWeaAssociativeSearch, WeaError } = getEcCom();
        const { WeaSwitch } = getComsMobx();
        const { selectNextFlowStore } = this.props;
        const { form, condition } = selectNextFlowStore;
        return (
            <div className="wf-select-next-flow">
                <div className="wf-select-next-flow-content">
                    <WeaRightMenu {...this.getMoreBtns()}>
                        {this.getConditions()}
                    </WeaRightMenu>
                </div>
                <WeaDialogFooter buttons={this.getButtons()} moreBtn={this.getMoreBtns()} />
                <NodeInfo selectNextFlowStore={selectNextFlowStore} />
            </div>
        );
    }

    getConditions() {
        const { Button, message } = getAntd();
        const { WeaDialogFooter, WeaRightMenu, WeaSearchGroup, WeaFormItem,WeaBrowser, WeaError } = getEcCom();
        const { WeaSwitch } = getComsMobx();
        const { selectNextFlowStore } = this.props;
        let { form, nextNodeIds, nodeInfo, nodeInfoMap = {}, baseParams = {}, nodeScope, operatorChangeDisable, groupList, nodeAttribute, branchNodesMap } = selectNextFlowStore;
        let groups = [];
        const isFormInit = form && form.isFormInit || false;
        const formParams = form && form.getFormParams() || {};

        // 获取节点浏览按钮的显示数据
        let replaceDatas = [];
        //选择分叉中间点时，要过滤已选择分支的其他分叉中间点
        let notNodes = '';
        nextNodeIds.split(',').map((key) => {
            let nodeInfo = nodeInfoMap[key];
            branchNodesMap && Object.keys(branchNodesMap).map(branchMapKey => {
                if(branchNodesMap[branchMapKey] && branchNodesMap[branchMapKey].indexOf(key) > -1) {
                    notNodes += "," + branchNodesMap[branchMapKey].join(',');
                }
            })
            if (nodeInfo) {
                replaceDatas.push({id : key, name : nodeInfo.nodeName});
            }
        });
        let rediodata = mobx.toJS(nodeInfo);
        // let rediodata = [];
        // for(let key in nodeInfoMap){
        //     rediodata.push(nodeInfoMap[key]);
        // }
        let completeParams = {
            workflowid : baseParams.workflowid,
            noNeedActiveWfId : '1',
            nodes : nodeScope
        }
        if(notNodes != '') {
            notNodes = notNodes.substring(1);
            completeParams['notNodes'] = notNodes;
            completeParams['nodeattribute'] = '2';
        }
        replaceDatas.length>0?this.state.radiovalue = replaceDatas[0].id:'';
        groupList.map((group, index) => {
            let items = [];
            let condition = mobx.toJS(group.items);
            let title = group.title;
            let radioitems = [];
            isFormInit && condition.map((field) => {
                if (field.domkey[0].indexOf('nextNode') > -1) {
                    items.push({
                        com: (<WeaFormItem
                          label={`${field.label}`}
                          labelCol={{ span: `${field.labelcol}` }}
                          wrapperCol={{ span: `${field.fieldcol}` }}
                        >
                                <div className={'form-selectNextFlow-nodeBrowser'}>
                                    <WeaError tipPosition="bottom"
                                      ref={field.viewAttr == 3 ? 'nodeError' : 'nodeErrorNoUSE'}
                                      error={getLabel(390821, '"下一节点" 未填写')}
                                    >
                                        <RadioGroup onChange={(v)=>{
                                            this.onChange(v)
                                            }} value={this.state.radiovalue}>
                                            {
                                                rediodata.length>0&&rediodata.map((data,index)=>{
                                                    return <Radio key={index+1} value={data.key}>{data.nodeName}</Radio>
                                                })
                                            }
                                        </RadioGroup>
                                        <WeaBrowser
                                          type="workflowNode"
                                          completeParams={completeParams}
                                          onBrowerClick={this.showNodeInfoDialog}
                                          isSingle={nodeAttribute != '1'}
                                          replaceDatas={replaceDatas}
                                          onChange={this.onNodeBrowserChange}
                                          viewAttr={field.viewAttr}
                                          style={{display:'none'}}
                                        />
                                    </WeaError>
                                </div>
                            </WeaFormItem>),
                        colSpan: 1,
                    });
                } else {
                    if (field.domkey[0].indexOf('nodeOperator_') > -1) { // 选择节点， 操作者为必填， 没选择节点， 操作者为可编辑
                        field.viewAttr = (!nextNodeIds || nextNodeIds == '') ? 2 : 3;
                    }
                    if (operatorChangeDisable == '1' && (field.domkey[0].indexOf('nodeOperator') > -1 || field.domkey[0].indexOf('ccOperator') > -1)) { // 禁止修改操作者
                        field.viewAttr = 1;
                    }
                    items.push({
                        com: (<WeaFormItem
                          label={`${field.label}`}
                          labelCol={{ span: `${field.labelcol}` }}
                          wrapperCol={{ span: `${field.fieldcol}` }}
                          colon={field.domkey[0].indexOf('canSubmit_') == -1}
                          error={form.getError(field)}
                          tipPosition="bottom"
                        >
                                {field.domkey[0].indexOf('nodeOperator_') == -1 ?
                                    <WeaSwitch fieldConfig={field} form={form} formParams={formParams} /> :
                                    <div className={'form-selectNextFlow-nodeBrowser'}>
                                    <WeaError tipPosition="bottom"
                                      ref={field.viewAttr == 3 ? `operatorError_${field.domkey[0]}` : 'operatorErrorNoUSE'}
                                      error={`"${field.label}" ${getLabel(21423, '未填写')}`}
                                    >
                                        <WeaSwitch fieldConfig={field} form={form} formParams={formParams} />
                                    </WeaError>
                                </div>
                                }
                            </WeaFormItem>),
                        colSpan: 1,
                        hide: form.isHide(field, (keys, allParams) => {
                            const key = keys[0];
                            // if (key.indexOf('SignType_') > -1 || key.indexOf('canSubmit_') > -1) { // 禁止修改操作者，会签方式隐藏
                            //     return operatorChangeDisable == '1';
                            // }
                            if(key.indexOf('SignType_') > -1 || key.indexOf('canSubmit_') > -1 || key.indexOf('ccOperator_') > -1){
                                return true;
                            }
                            return false;
                        }),
                    });
                }
            });
            isFormInit && groups.push(<WeaSearchGroup title={nodeAttribute == '1' ? title : ''} needTigger={nodeAttribute == '1'} showGroup={true} items={items} col={1} />);
        });
        return <div>{groups}</div>;
    }

    onChange(e) {
        const { radiovalue } = this.state;
        const { selectNextFlowStore } = this.props;
        const { nodeInfoMap = {} } = selectNextFlowStore;
        this.setState({
            radiovalue: e.target.value,
        });
        let rediodata = [];
        let changedata = [];
        for(let key in nodeInfoMap){
            rediodata.push(nodeInfoMap[key]);
        }
        rediodata.map(data=>{
            if(data.key == e.target.value){
                changedata.push({id:data.key, name:data.nodeName})
            }
        })
        this.onNodeBrowserChange('','',changedata);
    }
    onNodeBrowserChange = (ids, names, datas) => {
        const { selectNextFlowStore } = this.props;
        const { changeNextNode, updateFormByNodeInfo, nextNodeIds, nodeInfoMap } = selectNextFlowStore;
        let newNextNodeIds = '';
        datas.map(data => {
            //已选择节点不是分叉中间节点，用最后一个节点替换当前选择的节点
            if(nodeInfoMap[nextNodeIds] && nodeInfoMap[nextNodeIds].nodeAttribute != 2) {
                newNextNodeIds = ',' + data.id;//替换
            } else {
                newNextNodeIds += ',' + data.id;//增加
            }
        })
        if(newNextNodeIds != '') {
            newNextNodeIds = newNextNodeIds.substring(1);
        }
        changeNextNode(newNextNodeIds);
    }

    getButtons() {
        const { Button, message } = getAntd();
        const { WeaDialogFooter, WeaRightMenu, WeaSearchGroup, WeaFormItem, BaseWeaAssociativeSearch, WeaError } = getEcCom();
        let buttons = [];
        buttons.push(<Button type="primary" disabled={this.state.isSubmit} onClick={this.doConfirm}>{getLabel(83446, '确定')}</Button>);
        return buttons;
    }
    getMoreBtns() {
        let btns = [];
        btns.push({
            key: '0',
            icon: <i className="icon-coms-Preservation" />,
            content: getLabel(83446, '确定'),
            disabled: this.state.isSubmit,
            onClick: key => this.doConfirm(),
        });
        return { datas: btns };
    }

    doConfirm = () => {
        const { selectNextFlowStore } = this.props;
        const { form, nextNodeIds,nodeAttribute,nodeInfoMap,branchNodesMap,mustPassNodeIds } = selectNextFlowStore;
        const { message, Modal } = getAntd();
        const that = this;
        const formParams = form.getFormParams();

        let showErrorTip = () => {
            Modal.warning({
                title: getLabel(131329, ' 信息确认'),
                content: `${getLabel(384146, '必要信息不完整，红色*为必填项')}！`,
                okText: getLabel(83446, '确定'),
                onOk() { },
            });
        }

        //验证节点必填
        if ((!nextNodeIds || nextNodeIds == '') && this.refs.nodeError) {
            showErrorTip();
            return;
        }

        //验证操作者必填
        let checkNodeIds = nextNodeIds.split(',');
        let operatorCheck = true;
        checkNodeIds.map((nextNodeId, index) => {
            if ((!formParams[`nodeOperator_${index}`] || formParams[`nodeOperator_${index}`] == '') && this.refs[`${'operatorError_' + 'nodeOperator_'}${index}`]) {
                operatorCheck = false;
            }
        });
        if(!operatorCheck) {
            showErrorTip();
            return;
        }

        //分叉起始点，指定流转不是主干节点的情况下，检查是否选择了必须经过的分支
        if(nodeAttribute == '1' && !(checkNodeIds.length == 1 && nodeInfoMap[checkNodeIds[0]].nodeAttribute != '2')) {
            let mustPassCheck = true;
            mustPassNodeIds && mustPassNodeIds.map(id => {
                if(!this.checkSameElement(checkNodeIds, branchNodesMap[id])) {
                    mustPassCheck = false;
                }
            })
            if(!mustPassCheck) {
                Modal.warning({
                    content: getLabel(528903,"请选择必须通过的分支上的节点"),
                    okText:getLabel(83446,"确定"),
                    onOk() {
                    },
                });
                return;
            }
        }

        form.validateForm().then((f) => {
            if (f.isValid) {
                const result = selectNextFlowStore.getResultParams();
                that.setState({ isSubmit: true });
                message.loading(getLabel(83922, '正在提交流程,请稍候...'), 0);
                selectNextFlowStore.confirmEvent(result);
            } else {
                showErrorTip();
                // f.showErrors();
            }
        });
    }

    //检查两个列表是否有共同的元素
    checkSameElement = (nodeList, checkList) => {
        let result = false;
        checkList && checkList.map(v1 => {
            if(nodeList && nodeList.indexOf(v1) > -1) {
                result = true;
            }
        })
        return result;
    }

    showNodeInfoDialog = () => {
        const { globalStore, selectNextFlowStore } = this.props;

        selectNextFlowStore.setNodeInfoConfirmEvent((rejectParams) => {
            globalStore.controlDialogVisible(type.SELECT_NEXTFLOW_NODEINFO, false);
        });
        selectNextFlowStore.setNodeInfoCancelEvent(() => {
            globalStore.controlDialogVisible(type.SELECT_NEXTFLOW_NODEINFO, false);
        });
        globalStore.controlDialogVisible(type.SELECT_NEXTFLOW_NODEINFO, true);		// 需最后显示弹窗
    }
}
